package org.linuxsogood.boot.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author honway.liu
 * @date 2019-07-31 18:30
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 *
 * CountDownLatch 原子计数器类,主要用于计数.
 * 构造给一个初始值,比如20, 每次调用countDown方法时会减1,直到减到0
 * await方法后面的代码,才会继续执行.
 */
public class CountDownLatchExample1 {
    private static int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            executorService.execute(() -> {
                try {
                    method();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await();
        System.out.println("finished...");
        executorService.shutdown();
    }

    private static void method() throws InterruptedException {
        System.out.println("current thread name: " + Thread.currentThread().getName());
        TimeUnit.MILLISECONDS.sleep(100);
    }
}
